package com.meteor.controller;

import com.meteor.pojo.*;
import com.meteor.service.*;
import org.aspectj.weaver.ast.Or;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {

    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd yy:MM:ss");

    @Resource
    private OrderService orderService;

    @Resource
    private UserService userService;

    @Resource
    private ShopService shopService;

    @Resource
    private BookService bookService;

    @Resource
    private ItemService itemService;

    // 查询所有订单
    @GetMapping("/selectAllOrder")
    public String selectAllOrder(Model model) {
        List<Order> orders = orderService.selectAllOrder();
        model.addAttribute("orders", orders);
        return "back/order";
    }

    // 更新订单信息
    @GetMapping("/updateOrder")
    public String updateOrderById(Order order,Model model) {
        if(order != null) {
            int i = orderService.updateOrderById(order);
            List<Order> orders = orderService.selectAllOrder();
            model.addAttribute("orders", orders);
            if(i > 0) {
                model.addAttribute("message", "修改订单信息成功");
            }else {
                model.addAttribute("message", "修改订单信息失败");
            }
        }
        return "back/order::tab";
    }


    // 新增订单 支付成功
    @GetMapping("/insertOrder")
    @Transactional
    public String insertOrder(Order order, HttpServletRequest request) {
        User user =(User) request.getSession().getAttribute("user");
        // 拿到我们付款书籍id
        Integer[] arr =(Integer[]) request.getSession().getAttribute("arr");
        Date date = new Date();
        order.setCreateTime(sf.format(date));
        order.setUserId(user.getId());

        // 通过bookId们批量获取Shop，此时我们能拿到每一个shopId与count
        List<Shop> shops = shopService.selectShopByBookId(arr);

        // 0. 先判断自己的金额是否支持付款，支持的话将自己的金额修改
        if(user.getMoney() >= order.getPayMoney()) {
            // 新增订单
            int orderId = orderService.insertOrder(order);
            user.setMoney(user.getMoney() - order.getPayMoney());
            userService.updateUserMoney(user.getMoney(), user.getUsername());

            // 再将库存数量修改
            // 总数量减少、售出数量增加
            for (int j = 0; j < shops.size(); j++) {
                Integer bookId = shops.get(j).getBookId();
                Book book = bookService.selectBookById(bookId);
                // 曾经的总数量、售出量
                Integer allCount = book.getAllCount();
                Integer sellCount = book.getSellCount();
                // 本次售出数量
                Integer count = shops.get(j).getCount();
                if(allCount < count) {
                    request.setAttribute("message", "商品数量不足，支付失败!");
                    return "front/pay";
                }

                book.setAllCount(allCount - count);
                book.setSellCount(sellCount + count);
                // 数量更新
                bookService.updateCountByBookId(book);

                // 1. 通过拿到的bookId，获取购物车中的shopId
                Integer shopId = shops.get(j).getId();
                // 2. 在获取order表中新插入生成的id
                // 3. 再将shopId 插入到item表中
                itemService.insertItem(order.getId(), shopId,bookId,count);
                // 4. 支付成功后将购物车中的商品删除
                shopService.deleteByBookId(bookId);
            }
            request.setAttribute("message", "恭喜您，支付成功！");
        }else {
            request.setAttribute("message", "余额不足，支付失败，请充值！");
        }
        return "front/pay";
    }


    // 查询所有订单信息到 订单详情页面
    @GetMapping("/selectOrderLastAll")
    public String selectOrderLastAll(Model model, HttpSession session) {

        User user =(User) session.getAttribute("user");

        List<OrderDto> orderDtos = orderService.selectOrderLastAll();
        ArrayList<OrderDto> list = new ArrayList<>();
        int size = orderDtos.size();


        for (int i = 0; i < size; i++) {
            if(orderDtos.get(i).getUserId() == user.getId()) {
                list.add(orderDtos.get(i));
            }
        }
        model.addAttribute("orderDtos", list);
        return "front/orderDetail";
    }




}















